﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LPLS.Commons.Exten
{
    public static class DynamicConverter
    {
        // 主转换方法
        public static dynamic ToStronglyTypedDynamic(this Dictionary<string, object> dict)
        {
            var expando = new ExpandoObject();
            var expandoDict = (IDictionary<string, object>)expando;

            foreach (var kvp in dict)
            {
                // 递归处理嵌套字典
                if (kvp.Value is Dictionary<string, object> nestedDict)
                {
                    expandoDict[kvp.Key] = nestedDict.ToStronglyTypedDynamic();
                }
                // 处理字典列表
                else if (kvp.Value is IEnumerable<object> list)
                {
                    expandoDict[kvp.Key] = list
                        .Select(item => item is Dictionary<string, object> itemDict
                            ? itemDict.ToStronglyTypedDynamic()
                            : item)
                        .ToList();
                }
                // 处理简单类型
                else
                {
                    expandoDict[kvp.Key] = kvp.Value;
                }
            }

            return expando;
        }
    }
}
